//
//  LLBannerView.m
//  PandaMakeUp
//
//  Created by dl on 15/12/15.
//  Copyright © 2015年 lrlz. All rights reserved.
//

#define BannerDuration 4.f

typedef NS_ENUM(uint, LLBannerScrollDirection) {
    LLBannerScrollDirectionNone = 1u << 0,  // NONE
    LLBannerScrollDirectionPre = 1u << 1,  // 上一页
    LLBannerScrollDirectionNext = 1u << 2   // 下一页
};

#import "LLBannerView.h"

@interface LLBannerView () <UIScrollViewDelegate>
@property(nonatomic, assign) LLBannerScrollDirection scrollDirection;

// 当前显示的图片的index
@property(nonatomic, readwrite, assign) NSInteger curIndex;
// 当前显示的LLUIImageView的index
@property(nonatomic, assign) NSInteger curItemIndex;

@property(nonatomic, strong) NSArray<LLUIImageView *> *threeItems;
@end

@implementation LLBannerView {
    UIScrollView *scrollView;
    UIPageControl *control;

    NSTimer *bannerTimer;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self reset];
}

#pragma mark -
#pragma mark life cycle

- (instancetype)init {
    self = [super init];
    if (self) {
        [self reset];
    }
    return self;
}

- (void)reset {
    self.options = LLBannerViewPageControllMidCenter;
    self.scrollDirection = LLBannerScrollDirectionNone;

    scrollView = [UIScrollView new];
    scrollView.delegate = self;
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.alwaysBounceHorizontal = YES;
    [scrollView setScrollsToTop:NO];
    scrollView.backgroundColor = UI_COLOR_BG_GREY;
    [self addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.height.width.equalTo(self);
    }];

    control = [[UIPageControl alloc] init];
    [self addSubview:control];

    self.lightedPageControlImg = [UIImage imageNamed:@"goods_slider_red"];
    self.normalPageControlImg = [UIImage imageNamed:@"goods_slider"];

    self.curIndex = 0;
    control.numberOfPages = 0;

    LLUIImageView *firstItem = [LLUIImageView new];
    [scrollView addSubview:firstItem];
    LLUIImageView *secondItem = [LLUIImageView new];
    [scrollView addSubview:secondItem];
    LLUIImageView *thirdItem = [LLUIImageView new];
    [scrollView addSubview:thirdItem];
    _threeItems = @[firstItem, secondItem, thirdItem];
    _curItemIndex = 1;
}

- (void)dealloc {
    if ([bannerTimer isValid]) {
        [bannerTimer invalidate];
        bannerTimer = nil;
    }
}

#pragma mark -
#pragma mark layout

- (void)layoutSubviews {
    if (self.imgUrls.count > 0) {
        [control mas_makeConstraints:^(MASConstraintMaker *make) {
            if (self.options & LLBannerViewPageControllLeftBottom) {
                make.left.equalTo(self).offset(SUIT_W(20));
            } else if (self.options & LLBannerViewPageControllMidCenter) {
                make.centerX.equalTo(self);
            } else if (self.options & LLBannerViewPageControllLeftRight) {
                make.right.equalTo(self).offset(SUIT_W(20));
            }
            make.bottom.equalTo(self).offset(SUIT_W(-24));
            make.width.mas_equalTo(SUIT_W(20) * self.imgUrls.count);
            make.height.mas_equalTo(SUIT_H(10));
        }];
        // 居左
        [_threeItems[0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.width.height.equalTo(scrollView);
        }];
        // 居中
        [_threeItems[1] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.width.height.equalTo(scrollView);
        }];
        // 居右
        [_threeItems[2] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.width.height.equalTo(scrollView);
        }];

        _threeItems[1].transform = CGAffineTransformMakeTranslation(self.ll_width, 0);
        _threeItems[2].transform = CGAffineTransformMakeTranslation(2 * self.ll_width, 0);

        scrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, 0);
        scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
        control.currentPage = self.curIndex;
    }
    [self updateDots];
}

- (void)setImgUrls:(NSArray<NSString *> *)imgUrls {
    if (_imgUrls != imgUrls) {
        _imgUrls = imgUrls;

        self.curIndex = (self.curIndex >= _imgUrls.count ? 0 : self.curIndex);
        self.curIndex = _imgUrls.count > 1 ? 1 : self.curIndex;
        control.numberOfPages = _imgUrls.count;

        [_threeItems[0] setImageUrlStr:_imgUrls[[self getPreIndex]]];
        [_threeItems[1] setImageUrlStr:_imgUrls[self.curIndex]];
        [_threeItems[2] setImageUrlStr:_imgUrls[[self getNextIndex]]];

        [self setNeedsLayout];
    }
}

- (void)setClickItemBlock:(void (^)(NSInteger))clickItemBlock {
    if (_clickItemBlock != clickItemBlock) {
        _clickItemBlock = [clickItemBlock copy];

        @weakify(self)
        [_threeItems[0] setClickBlock:^{
            @strongify(self)
            self.clickItemBlock([self curIndex]);
        }];
        [_threeItems[1] setClickBlock:^{
            @strongify(self)
            self.clickItemBlock([self curIndex]);
        }];
        [_threeItems[2] setClickBlock:^{
            @strongify(self)
            self.clickItemBlock([self curIndex]);
        }];
    }
}

- (void)setOptions:(LLBannerViewOptions)options {
    if (_options != options) {
        _options = options;

        if (_options & LLBannerViewAutoScroll) {
            if ([bannerTimer isValid]) {
                [bannerTimer invalidate];
                bannerTimer = nil;
            }
            bannerTimer = [NSTimer scheduledTimerWithTimeInterval:BannerDuration target:self selector:@selector(scrollToNestWithTimer) userInfo:nil repeats:YES];
        }
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if ([bannerTimer isValid]) {
        [bannerTimer invalidate];
        bannerTimer = nil;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)aScrollView willDecelerate:(BOOL)decelerate {
    // 拖动结束时，禁用scrollView的滚动
    aScrollView.scrollEnabled = NO;
    if (_options & LLBannerViewAutoScroll && (bannerTimer == nil || ![bannerTimer isValid])) {
        bannerTimer = [NSTimer scheduledTimerWithTimeInterval:BannerDuration target:self selector:@selector(scrollToNestWithTimer) userInfo:nil repeats:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView {
    int minus = aScrollView.ll_width - aScrollView.contentOffset.x;
    if (minus == 0) {
        self.scrollDirection = LLBannerScrollDirectionNone;
    } else if (minus > 0) {
        self.scrollDirection = LLBannerScrollDirectionPre;
        self.curIndex = [self getPreIndex];
    } else {
        self.scrollDirection = LLBannerScrollDirectionNext;
        self.curIndex = [self getNextIndex];
    }

    control.currentPage = self.curIndex;
    [self updateDots];
}

#pragma mark -
#pragma mark event

- (void)scrollToNestWithTimer {
    scrollView.scrollEnabled = NO;
    self.scrollDirection = LLBannerScrollDirectionNext;
    [UIView animateWithDuration:0.5f animations:^{
        scrollView.contentOffset = CGPointMake(2 * scrollView.ll_width, 0);
    }                completion:^(BOOL finished) {
        self.curIndex = [self getNextIndex];
        control.currentPage = self.curIndex;
        [self updateDots];
    }];
}

- (void)updateDots {
    [self resetPosition];
    for (int i = 0; i < [control.subviews count]; i++) {
        UIView *dot = [control.subviews objectAtIndex:i];
        dot.ll_size = self.lightedPageControlImg.size;
        if (i == self.curIndex) {
            dot.backgroundColor = [UIColor colorWithPatternImage:self.lightedPageControlImg];
        } else {
            dot.backgroundColor = [UIColor colorWithPatternImage:self.normalPageControlImg];
        }
    }
}

- (void)resetPosition {
    scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
    if (_scrollDirection == LLBannerScrollDirectionPre) {
        [self getNextItem].transform = CGAffineTransformIdentity;
        [self getCurItem].transform = CGAffineTransformMakeTranslation(2 * scrollView.ll_width, 0);
        [self getPreItem].transform = CGAffineTransformMakeTranslation(scrollView.ll_width, 0);

        _curItemIndex = _curItemIndex == 0 ? 2 : (_curItemIndex - 1);
        [[self getPreItem] setImageUrlStr:_imgUrls[[self getPreIndex]] size:IMAGE_SIZE_ORIGIN];
    } else if (_scrollDirection == LLBannerScrollDirectionNext) {
        [self getNextItem].transform = CGAffineTransformMakeTranslation(scrollView.ll_width, 0);
        [self getCurItem].transform = CGAffineTransformIdentity;
        [self getPreItem].transform = CGAffineTransformMakeTranslation(2 * scrollView.ll_width, 0);

        _curItemIndex = _curItemIndex == 2 ? 0 : (_curItemIndex + 1);
        [[self getNextItem] setImageUrlStr:_imgUrls[[self getNextIndex]] size:IMAGE_SIZE_ORIGIN];
    }
    // 完成转换之后，启用scrollView的滚动
    scrollView.scrollEnabled = YES;
    self.scrollDirection = LLBannerScrollDirectionNone;
}

// 获取上一个、下一个的index
- (NSInteger)getPreIndex {
    return self.curIndex <= 0 ? (_imgUrls.count - 1) : (self.curIndex - 1);
}

- (NSInteger)getNextIndex {
    return self.curIndex >= (_imgUrls.count - 1) ? 0 : (self.curIndex + 1);
}

// 获取前一个、当前显示的、下一个item
- (LLUIImageView *)getCurItem {
    return _threeItems[_curItemIndex];
}

- (LLUIImageView *)getPreItem {
    NSInteger preItemIndex = _curItemIndex == 0 ? 2 : (_curItemIndex - 1);
    return _threeItems[preItemIndex];
}

- (LLUIImageView *)getNextItem {
    NSInteger nextItemIndex = _curItemIndex == 2 ? 0 : (_curItemIndex + 1);
    return _threeItems[nextItemIndex];
}

- (void)stopTimer {
    if ([bannerTimer isValid]) {
        [bannerTimer invalidate];
        bannerTimer = nil;
    }
}

- (void)startTimer {
    if (!bannerTimer) {
        bannerTimer = [NSTimer scheduledTimerWithTimeInterval:BannerDuration target:self selector:@selector(scrollToNestWithTimer) userInfo:nil repeats:YES];
    }
}

@end
